// pages/cart/index.js
import { getDefAddress, getCarData, resetCarCheck, delCarGoods, carGoodsNumber } from '../../api/index'
import { hidePhone, showToastUtil } from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    info: {},
    addHas: false,//是否有地址
    goodsList: [],//销售商品
    faileList: [],//下架商品
    total: 0,
    totalPrice: 0,
    allcheck: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  // onLoad: function (options) {
  //   this.defAddress()
  // },
  onShow: function () {
    this.defAddress()
    this.carGoodsList()
  },
  // 获取默认收货地址-未明确-获取地址列表第一项
  defAddress() {
    getDefAddress().then(res => {
      const { info = {} } = res.data
      let dataInfo = [info].map(v => {
        return {
          ...v,
          hidMobile: hidePhone(v.mobile)
        }
      })
      if (res.code === 0) {
        this.setData({ info: dataInfo[0], addHas: true })
      }
    })
  },
  // 购物车内商品列表
  carGoodsList() {
    getCarData().then(res => {
      const type = res.code === 0 ? true : false
      let number = 0;
      let price = 0;
      let items = [];
      if (type) {
        number = res.data.number, price = res.data.price, items = res.data.items
      }
      const goodsList = items.filter(v => v.status === 0)
      const faileList = items.filter(v => v.status === 1)
      const checkedList = goodsList.filter(v => v.selected === true)
      const allcheck = goodsList.length === checkedList.length && goodsList.length > 0 ? true : false
      console.log('=============', res, type)
      this.setData({ total: number || 0, totalPrice: price || 0, goodsList, faileList, allcheck })
    })
  },
  // 修改商品选中状态
  selectGoods(e) {
    const { item } = e.target.dataset
    const { selected, key } = item
    let type = selected ? false : true
    const params = {
      key,
      selected: type
    }
    resetCarCheck(params).then(res => {
      this.carGoodsList()
    })
  },
  // 删除购物车商品
  delGoods(e) {
    const { item } = e.target.dataset
    const { key } = item
    const params = {
      key
    }
    wx.showModal({
      title: '确认删除该商品？',
      content: '',
      showCancel: true,
      cancelText: '取消',
      cancelColor: '#000000',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: (result) => {
        if (result.confirm) {
          delCarGoods(params).then(res => {
            this.carGoodsList()
          })
        }
      },
      fail: () => { },
      complete: () => { }
    });
  },
  // 修改购物车某商品数量
  numGoods(e) {
    const { item, type } = e.target.dataset
    const { key, number } = item

    let num = type === 'reduce' ? number - 1 : number + 1
    const params = {
      key,
      number: num
    }
    carGoodsNumber(params).then(res => {
      this.carGoodsList()
    })
  },
  // 跳转商品详情
  goodsDetail(e) {
    const { goodsid } = e.target.dataset
    wx.navigateTo({
      url: '/pages/goods_detail/index?goodsid=' + goodsid,
    });
  },
  // 点击全选
  allSelected() {
    const { goodsList } = this.data
    const keyList = goodsList.reduce((pre, cur, index) => {
      if (index === goodsList.length - 1) {
        pre += cur.key
      } else {
        pre += `${cur.key},`
      }
      return pre
    }, '')
    this.setData({ allcheck: !this.data.allcheck }, () => {
      const params = {
        key: keyList,
        selected: this.data.allcheck
      }
      resetCarCheck(params).then(res => {
        this.carGoodsList()
      })
    })
  },
  // 数量输入框变化
  inpNum(e) {
    const { value } = e.detail
    const { key, stores } = e.target.dataset
    let number = Number(value)
    // 判断数量
    if (number < 1) {
      number = 1
    } else if (number > stores) {
      number = stores
    }
    const params = {
      key,
      number,
    }
    carGoodsNumber(params).then(res => {
      this.carGoodsList()
    })
  },
  // 去结算
  goPay() {
    const { addHas } = this.data
    if (!addHas) {
      showToastUtil('请添加收货地址')
    } else {
      wx.navigateTo({
        url: "/pages/pay/index"
      })
    }
  }
})